<template>
  <div class="rich-text">
    <div class="btn-group">
      <a-button-group>
        <a-button class="right" type="primary" @click="exportWords"
          >导出words</a-button
        >
        <a-button class="right" type="primary" @click="previewRichText"
          >预览</a-button
        >
      </a-button-group>
    </div>
    <div class="rich-input">
      <div class="rich-input-refs" id="rich-input-refs"></div>
    </div>
    <a-modal
      :bodyStyle="styles"
      v-model="visible"
      title="预览"
      width="60%"
      @ok="handleOk"
      okText="导出pdf"
      cancelText="关闭"
    >
      <div class="rich-output-refs" id="container" ref="rich-output-refs">
        <div v-html="htmlContent"></div>
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

import WEditor from "wangeditor";
import { asBlob } from "html-docx-js-typescript";
// if you want to save the docx file, you need import 'file-saver'
import { saveAs } from "file-saver";
import styles from "./richtext";

import { jsPDF } from "jspdf";
import htmlToCanvas from "html2canvas";

@Component({
  components: {},
})
export default class RichText extends Vue {
  private editor: any = null;
  private visible: boolean = false;
  private styles: object = styles;
  private htmlContent: any = "暂缺～";
  private jspdf: any = null;
  constructor() {
    super();
  }
  public mounted() {
    this.editor = new WEditor("#rich-input-refs");
    this.editor.config.height = 700;
    this.editor.config.zIndex = 1;
    this.editor.create();

    this.editor.config.onchange = (newHtml: any) => {
      this.htmlContent = newHtml;
    };
  }
  public exportWords() {
    console.log(this.htmlContent);
    if (this.htmlContent != "暂缺～") {
      this.ExpHtmlToWord(this.htmlContent);
    } else {
      this.$message.info("请输入文档内容");
    }
  }
  public exportPdf() {
    if (!this.jspdf) {
      this.jspdf = new jsPDF();
      let dom: any = document.getElementById("container");
      htmlToCanvas(dom).then((canvas) => {
        let url = canvas.toDataURL("image/png", 1);
        this.jspdf.addImage(url, "png", 0, 0);
        this.jspdf.save(
          `export${parseInt((Math.random() * 100000).toString())}.pdf`
        );
        this.jspdf = null;
      });
    }
  }
  public previewRichText() {
    this.visible = true;
  }
  public ExpHtmlToWord(eDiv: any) {
    asBlob(eDiv).then((data: any) => {
      saveAs(data, `file${parseInt((Math.random() * 10000).toString())}.docx`); // save as docx file
    }); // asBlob() return Promise<Blob|Buffer>
  }
  public handleOk() {
    this.exportPdf();
  }
}
</script>
<style lang="less" scoped>
.rich-text {
  padding: 10px;
  .rich-input {
    margin-top: 10px;
  }
  .rich-output-refs {
    min-height: 300px;
  }
}
</style>